angular.module('SmartCanteenApp.item_sales_report', ['ngRoute', 'ngTouch'])

	.config(['$routeProvider', function($routeProvider) {
		$routeProvider.when('/productMark', {  // 新服务中的生产业绩
			templateUrl: 'newReports/productMark.html',
			controller: 'productMarktCtrl'
		});
	}])
	//餐卡信息列表
	.controller('productMarktCtrl', ['$scope', '$timeout','$filter', function($scope, $timeout,$filter) {
		$('#datepicker').daterangepicker()                      
		//导出请求
		$scope.outPut = function(){
			var target
			if($scope.code == 0){
				target = $('#byChef')
				$scope.download('bychefdown','生产业绩-按厨师')
			}else if($scope.code == 1){
				target = $('#byitemdown')
				$scope.download('byitemdown','生产业绩-按菜品')
			}
			console.log(target)
		}
		
         
        
		//打印请求
		$scope.outPrint = function(){
			var html = null
			if($scope.code == 0){
				html = $("#bychefdown")
			}else if($scope.code == 1){
				html = $("#byitemdown")
			}
			$scope.printHtml(html[0].innerHTML);
		}
		//基础数据请求
		//1.1请求所有厨师
		$scope.getChef = function(){
			$scope.getReport($scope.reportPath+'commonLittleService/v1/allChef?canteenId='+$scope.canteenId,'','get',function(data){
				$scope.chefs = data.data
			})
//			$scope.chefs = [
//				{"user_id":"1","real_name":"厨师1"},
//				{"user_id":"3","real_name":"厨师2"},
//				{"user_id":"2","real_name":"厨师3"},
//				{"user_id":"4","real_name":"厨师4"},
//			]
		}
		//1.2请求所有档口
		$scope.getWindows = function(){
			$scope.getReport($scope.reportPath+'commonLittleService/v1/allWindow?canteenId='+$scope.canteenId,'','get',function(data){
				$scope.windows = data.data
			})
//			$scope.windows = [
//				{"window_id":"1","name":"档口1"},
//				{"window_id":"3","name":"档口2"},
//				{"window_id":"2","name":"档口3"},
//				{"window_id":"4","name":"档口4"},
//			]
		}
		//1.3请求所有菜品类别
		$scope.getCategorys = function(){
			$scope.getReport($scope.reportPath+'commonLittleService/v1/allCategory?canteenId='+$scope.canteenId,'','get',function(data){
				$scope.categorys = data.data
				$scope.allCategorys = data.data.concat()
			})
		}
		//get cId
		if( $scope.getCanteenId() != ''){
			$scope.canteenId =  $scope.getCanteenId() ;
		   	//获取基础数据
			$scope.getWindows();
			$scope.getChef();
			$scope.getCategorys()
		}
		$scope.$on('to-child', function(event,data) {
			//获取从父控制器传来的当前选中食堂
			$scope.canteenId = data;
			//获取基础数据
			$scope.getWindows();
			$scope.getChef();
			$scope.getCategorys()
		});
		//按厨师和按菜品切换 切换时保留数据
		$scope.code = 0
		$scope.chefOrItem = function(code,e){
			$scope.pagination([])
			$scope.sort = ''
            $scope.desc = undefined
			console.log($scope.byItem,$scope.byChef,$scope.code)
			if($scope.code == 1){
				$scope.pagination($scope.byChef)
			}else{
				$scope.pagination($scope.byItem)
			}
			
			if($scope.code == code){
				return
			}else{
				$scope.code = code				
				$('.coi').removeClass('btn-primary')
				$(e.target).addClass('btn-primary')
			}
			
		}
		//---------------列表
//		$scope.simpleList=[
//			{"chef_user_id":"1","chef_real_name":"11","sale_number":2,"sale_money":2,"profit":1},
//			{"chef_user_id":"1","chef_real_name":"11","sale_number":3,"sale_money":1,"profit":1},
//			{"chef_user_id":"1","chef_real_name":"11","sale_number":1,"sale_money":3,"profit":1},
//		];
		//按菜品查询 当档口变化时候类别的联动
		$scope.getCinW = function(){
			console.log($scope.searchByItem.window)
			if($scope.searchByItem.window == null){
				$scope.categorys = $scope.allCategorys
			}else{
				$scope.getReport($scope.reportPath+'commonLittleService/v1/allCategoryByWindow?windowId='+$scope.searchByItem.window,'','get',function(data){
					$scope.categorys = data.data
				})
			}
		}
		//数据查询请求
		$scope.simpleList = []
		//1.1数据初始化
		$scope.searchDate = $scope.getNowFormatDate()+' 至 '+$scope.getNowFormatDate()
		$scope.searchByChef = {
			"id":""
		}
		$scope.searchByItem = {
			"chef":"",
			"window":"",
			"category":""
		}
		//1.2查询
		$scope.searchProductByChef = function(){
			if($scope.searchByChef.id == null){
				$scope.searchByChef = {
					"id":""
				}
			}
			var datearr = $scope.searchDate.split(' 至 ')
			console.log($scope.searchByChef,datearr)
			var url = $scope.reportPath+'productionService/v1/pc/selectChefSaleByChef?startDate='+datearr[0]+'&endDate='+datearr[1]+'&canteenId='+$scope.canteenId+'&chefUserId='+$scope.searchByChef.id
			$scope.getReport(url,'','get',function(data){
				$scope.simpleList = data.data
				$scope.byChef = $scope.simpleList.concat()
				$scope.pagination($scope.simpleList)
			})
//			$scope.simpleList=[
//				{"chef_user_id":"1","chef_real_name":"11","sale_number":2,"sale_money":2,"profit":1},
//				{"chef_user_id":"1","chef_real_name":"11","sale_number":3,"sale_money":1,"profit":1},
//				{"chef_user_id":"1","chef_real_name":"11","sale_number":1,"sale_money":3,"profit":1},
//			];
//			$scope.byChef = $scope.simpleList.concat()
//			$scope.pagination($scope.simpleList)
		}
		$scope.search = {"itemName":""}
		$scope.searchProductByItem = function(){
			var datearr = $scope.searchDate.split(' 至 ')
			console.log($scope.searchByItem,datearr)
			$scope.search = {"itemName":""}
			if($scope.searchByItem.window == null || $scope.searchByItem.chef == null || $scope.searchByItem.category == null){
				$scope.searchByItem = {
					"chef":"",
					"window":"",
					"category":""
				}
			}
			var url = $scope.reportPath+'productionService/v1/pc/selectChefSaleByItem?startDate='+datearr[0]+'&endDate='+datearr[1]+'&canteenId='+$scope.canteenId+'&chefUserId='+$scope.searchByItem.chef+'&windowId='+$scope.searchByItem.window+'&categoryId='+$scope.searchByItem.category
			$scope.getReport(url,'','get',function(data){
				$scope.simpleList = data.data
				$scope.byItem = $scope.simpleList.concat()
				$scope.pagination($scope.simpleList)
			})
//			$scope.simpleList=[
//				{"chef_user_id":"1", "chef_real_name":"厨师1","item_id":"1","item_name":"菜品1","window_id":"1","window_name":"档口1","sale_number":1,"sale_money":1},
//				{"chef_user_id":"2", "chef_real_name":"厨师2","item_id":"2","item_name":"菜品2","window_id":"2","window_name":"档口2","sale_number":2,"sale_money":2},
//				{"chef_user_id":"3", "chef_real_name":"厨师3","item_id":"3","item_name":"菜品3","window_id":"3","window_name":"档口3","sale_number":3,"sale_money":3},
//				{"chef_user_id":"4", "chef_real_name":"厨师4","item_id":"4","item_name":"菜品4","window_id":"4","window_name":"档口4","sale_number":4,"sale_money":4},
//				{"chef_user_id":"5", "chef_real_name":"厨师5","item_id":"5","item_name":"菜品5","window_id":"5","window_name":"档口5","sale_number":5,"sale_money":5},
//				{"chef_user_id":"6", "chef_real_name":"厨师6","item_id":"6","item_name":"菜品6","window_id":"6","window_name":"档口6","sale_number":6,"sale_money":6},
//				{"chef_user_id":"7", "chef_real_name":"厨师7","item_id":"7","item_name":"菜品7","window_id":"7","window_name":"档口7","sale_number":7,"sale_money":7},
//				{"chef_user_id":"8", "chef_real_name":"厨师8","item_id":"8","item_name":"菜品8","window_id":"8","window_name":"档口8","sale_number":8,"sale_money":8},
//				{"chef_user_id":"9", "chef_real_name":"厨师9","item_id":"9","item_name":"菜品9","window_id":"9","window_name":"档口9","sale_number":9,"sale_money":9},
//				{"chef_user_id":"10", "chef_real_name":"厨师10","item_id":"10","item_name":"菜品10","window_id":"10","window_name":"档口10","sale_number":10,"sale_money":10},
//				{"chef_user_id":"11", "chef_real_name":"厨师11","item_id":"11","item_name":"菜品11","window_id":"11","window_name":"档口11","sale_number":11,"sale_money":11},
//				
//			];
//			$scope.byItem = $scope.simpleList.concat()
//			$scope.pagination($scope.simpleList)
		}
		//1.3模糊查询

			//1.3.1 监听变化 $scope.search.itemName
			$scope.$watch('search.itemName',function(){
				if($scope.search.itemName == undefined) {
					$scope.search.itemName = '';
				}
				//准备一个空的数组
				var newList = [];
				var arr = $scope.byItem;
				if(arr == undefined)
					return
				
				var length = $scope.byItem.length;
				for(var i = 0; i < length; i++) {
					if(arr[i].item_name.indexOf($scope.search.itemName) >= 0 ) {
						newList.push(arr[i]);
					}
				}
		
				$scope.pagination(newList);
			})
		
	    //分页----------------------
	    //每页展示数改变时调取此方法
				$scope.change = function( items ){
					console.log(items);
					$scope.pageSize = items ;//改变后的每页显示数
					$scope.pages = Math.ceil($scope.data.length / $scope.pageSize); //分页数
					$scope.newPages = $scope.pages > 5 ? 5 : $scope.pages;
					$scope.pageList = [];
					$scope.selPage = 1;
					$scope.items = $scope.data.slice(0, $scope.pageSize);
					//分页要repeat的数组
					for (var i = 0; i < $scope.newPages; i++) {
						$scope.pageList.push(i + 1);
					}
					//设置表格数据源(分页)
					$scope.setData = function () {
						$scope.items = $scope.data.slice(($scope.pageSize * ($scope.selPage - 1)), ($scope.selPage * $scope.pageSize));//通过当前页数筛选出表格当前显示数据
					}
				}
				//设置表格数据源(分页)
				$scope.setData = function () {
					if($scope.data == [] || $scope.data ==undefined || $scope.data =='undefined'){
						return;
					}
					$scope.items = $scope.data.slice(($scope.pageSize * ($scope.selPage - 1)), ($scope.selPage * $scope.pageSize));//通过当前页数筛选出表格当前显示数据
				}
				//打印当前选中页索引
				$scope.selectPage = function (page) {
					//不能小于1大于最大
					if (page < 1 || page > $scope.pages) return;
					//最多显示分页数5
					if (page > 2) {
					//因为只显示5个页数，大于2页开始分页转换
					var newpageList = [];
					for (var i = (page - 3) ; i < ((page + 2) > $scope.pages ? $scope.pages : (page + 2)) ; i++) {
					newpageList.push(i + 1);
					}
					$scope.pageList = newpageList;
					}
					$scope.selPage = page;
					$scope.setData();
					$scope.isActivePage(page);
					console.log("选择的页：" + $scope.selPage);
				};
				
				//设置当前选中页样式
				$scope.isActivePage = function (page) {
					return $scope.selPage == page;
				};
				//上一页
				$scope.Previous = function () {
					$scope.selectPage($scope.selPage - 1);
				}
				//下一页
				$scope.Next = function () {
					$scope.selectPage($scope.selPage + 1);
				};
				//初始条码
				$scope.pageList = [1];
				//初始每页查询数量
				$scope.initial = "10";
                //表格分页数据处理
                $scope.pagination = function(datas){
//              	console.log(datas);
                	$scope.data = datas;
					//总条目数
					if(datas != null){
						$scope.totalNums = 	$scope.data.length ;
						//分页总数
						$scope.pageSize = 10;
						$scope.pages = Math.ceil($scope.data.length / $scope.pageSize); //分页数
						$scope.newPages = $scope.pages > 5 ? 5 : $scope.pages;
						$scope.pageList = [];
						$scope.selPage = 1;
						$scope.page = 1
						$scope.items = $scope.data.slice(0, $scope.pageSize);
//						console.log($scope.items);
						//分页要repeat的数组
						for (var i = 0; i < $scope.newPages; i++) {
							$scope.pageList.push(i + 1);
						}
					}
					
                }
                $scope.pagination($scope.simpleList)
                //点击隐藏列 为加入页面
                $scope.head = [
                	{name:"姓名",id:1,checked:true},
                	{name:"年龄",id:2,checked:true},
                	{name:"性别",id:3,checked:true},
                	{name:"ID" ,id:4,checked:true},
                ]
                $scope.colName = true
                $scope.colAge  = true
                $scope.colSex  = true
                $scope.colId   = true
                
                $scope.col = function(checked,id,e){
                	e.stopPropagation()
                	console.log(checked,id)
                	if( id === 1 ){
                		$scope.colName = checked
                	}else if( id === 2 ){
                		$scope.colAge  = checked
                	}else if( id === 3 ){
                		$scope.colSex  = checked
                	}else if( id === 4 ){
                		$scope.colId  = checked
                	}
                }
                //排序 
                $scope.sort = ''
                $scope.desc = undefined
                $scope.sortBy = function(sort){
                	$scope.sort = sort
                	$scope.desc = !$scope.desc 
                	if($scope.code == 0){
                		$scope.simpleList = $filter('orderBy')($scope.byChef, [sort], $scope.desc)
                		$scope.pagination($scope.simpleList)
                	}else{
                		$scope.simpleList = $filter('orderBy')($scope.byItem, [sort], $scope.desc)
                		$scope.pagination($scope.simpleList)
                	}
                	
                }
            //列宽的改变
            $scope.stretch = function(){
            		var id = ""
           			if($scope.code == 0 ){
           				$scope.head = ["姓名","销售量","销售额","参考利润"]
           				id = "byChef"
           			}else{
           				$scope.head = ["厨师姓名","菜品名称","档口名称","销售量","销售额"]
           				id = "byItem"
           			}
           			//列宽度调整方法
           			var myTAbId = document.getElementById(id);
		            var tTD; //用来存储当前更改宽度的Table Cell,避免快速移动鼠标的问题   
		            var wData = {};
		            var unset = myTAbId.rows[0].cells.length - $scope.head.length;//不在headList遍历的列数
		            for (var j = 0; j < myTAbId.rows[0].cells.length; j++) {  
		                myTAbId.rows[0].cells[j].index = j;
		                if(unset - 1<j){
		                    myTAbId.rows[0].cells[j].onmousedown = function (event) {   
		                        //记录单元格    
		                        tTD = this;   
		                        if (event.offsetX > tTD.offsetWidth - 10) {   
		                            tTD.mouseDown = true;   
		                            tTD.oldX = event.clientX;   
		                            tTD.oldWidth = tTD.offsetWidth;   
		                        }    
		                    };   
		                    myTAbId.rows[0].cells[j].onmouseup = function (event) {   
		                        //结束宽度调整   
		                        if (tTD == undefined) tTD = this;   
		                        tTD.mouseDown = false;   
		                        tTD.style.cursor = 'default';   
		                        $scope.head[this.index-unset].width = tTD.width;
		                    };   
		                    myTAbId.rows[0].cells[j].onmousemove = function (event) {   
		                        //更改鼠标样式   
		                        if (event.offsetX > this.offsetWidth - 10)   
		                        this.style.cursor = 'col-resize';      
		                        else   
		                        this.style.cursor = 'default';   
		                        //取出暂存的Table Cell   
		                        if (tTD == undefined) tTD = this;   
		                        //调整宽度   
		                        if (tTD.mouseDown != null && tTD.mouseDown == true) { 
		                            
		                            tTD.style.cursor = 'default';   
		                            if (tTD.oldWidth + (event.clientX - tTD.oldX)>0)   
		                            tTD.width = tTD.oldWidth + (event.clientX - tTD.oldX);   
		                            //调整列宽   
		                            // tTD.style.width = tTD.width;   
		                            tTD.style.cursor = 'col-resize';     
		                            //调整该列中的每个Cell   
		                            myTAbId = tTD; while (myTAbId.tagName != 'TABLE') myTAbId = myTAbId.parentElement;   
		                            for (var k = 0; k < myTAbId.rows.length; k++) {   
		                                myTAbId.rows[k].cells[tTD.cellIndex].width = tTD.width;   
		                            }   
		                        }   
		                    };   
		                }  
		            }
        
           		}
            $scope.searchAll = function(){
            	if($scope.code == 0){
            		$scope.searchProductByChef()
            	}else if($scope.code == 1){
            		$scope.searchProductByItem()
            	}
            }
	}])
	.directive('repeatFinish', function($timeout) {
        return {
            restrict: 'A',
            link: function(scope, element, attr) {
                if(scope.$last === true) {
                    $timeout(function() {
                        scope.stretch()
                    });
                }
            }
        };
    });
	